import path from 'path-browserify'
import { isExternal } from './index'
import { MenuTypeEnum } from '@/enums/MenuTypeEnum'
import type { RouteLocationRaw, RouteRecordRaw, NavigationGuardNext, RouteLocationNormalized } from 'vue-router'
import type { MenuData } from '@/api/system/menu'
import router from '@/router/index'

const Layout = () => import('@/layout/index.vue')
const modules = import.meta.glob('../views/**/**.vue')
// glob 将会被转译为下面的样子：
// const modules = {
//   '../views/login/index.vue': () => import('../views/login/index.vue'),
//   '../views/home/index.vue': () => import('../views/home/index.vue')
// }

/**
 * 转换路由数据为组件
 */
export const transformRoutes = (routes: MenuData[]) => {
  const asyncRoutes: RouteRecordRaw[] = []
  routes.forEach(route => {
    if (route.type === MenuTypeEnum.BUTTON) return
    const tmpRoute = { meta: {} } as RouteRecordRaw
    // 顶级目录，替换为 Layout 组件
    if (route.type === MenuTypeEnum.CATALOG && route.component?.toString() === 'Layout') {
      tmpRoute.component = Layout
      tmpRoute.name = route.path
      tmpRoute.redirect = route.redirect
    } else {
      // 其他菜单，根据组件路径动态加载组件
      const component = modules[`../views/${route.component}.vue`]
      if (component) {
        tmpRoute.component = component
      } else {
        tmpRoute.component = modules['../views/error-page/404.vue']
      }
      tmpRoute.name = route.routeName
    }
    tmpRoute.path = route.path

    tmpRoute.meta.hidden = route.visible === 0
    tmpRoute.meta.title = route.name
    tmpRoute.meta.icon = route.icon
    tmpRoute.meta.keepAlive = route.keepAlive === 1
    tmpRoute.meta.alwaysShow = route.alwaysShow === 1
    tmpRoute.meta.type = route.type

    if (route.children && route.children.length > 0) {
      tmpRoute.children = transformRoutes(route.children)
    }

    asyncRoutes.push(tmpRoute)
  })

  return asyncRoutes
}

/**
 * 重定向到登录页
 */
export function redirectToLogin(to: RouteLocationNormalized, next: NavigationGuardNext) {
  const params = new URLSearchParams(to.query as Record<string, string>)
  const queryString = params.toString()
  const redirect = queryString ? `${to.path}?${queryString}` : to.path
  next(`/login?redirect=${encodeURIComponent(redirect)}`)
}

/**
 * 解析路径，将相对路径转换为绝对路径
 */
export function resolvePath(basePath: string, routePath: string) {
  if (isExternal(routePath)) {
    return routePath
  }
  if (isExternal(basePath)) {
    return basePath
  }

  // 组合父级路径和路由路径形成完整路径
  const fullPath = path.resolve(basePath, routePath)
  return fullPath
}

/**
 * 判断是否有权限
 * */
// export function hasAuth(value: string | string[], type: 'button' | 'role' = 'button') {
//   const { roles, perms } = useUserStore().userInfo

//   // 超级管理员 拥有所有权限
//   if (type === 'button' && roles.includes('ROOT')) {
//     return true
//   }

//   const auths = type === 'button' ? perms : roles
//   return typeof value === 'string' ? auths.includes(value) : value.some(perm => auths.includes(perm))
// }
/**
 * 详情路由跳转新窗口
 * @param {RouteLocationRaw} to 跳转路由参数
 */
export const routerNewWindow = (to: RouteLocationRaw) => {
  const url = router.resolve(to)
  window.open(url.href)
}
